package IO;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class Channel {
    private static void copyChannel() throws IOException {
        /*
         * 通过文件通道时间文件的复制
         * */
        //创建一个输入文件的通道
        FileChannel r = new FileInputStream("C:\\Users\\Administrator\\Desktop\\File\\van.txt").getChannel();
        //创建一个输出文件的通道
        FileChannel c = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\File\\f\\van.txt").getChannel();
        ByteBuffer bb = ByteBuffer.allocate(1024);
        while (r.read(bb)!=-1){
            bb.flip();
            c.write(bb);
            bb.clear();
        }
        r.close();
        c.close();
        System.out.println("copy success");
    }
    private static void randomAccessFileCopy() throws IOException {
        RandomAccessFile in = new RandomAccessFile("C:\\Users\\Administrator\\Desktop\\File\\van.txt","r");
        RandomAccessFile out = new RandomAccessFile("C:\\Users\\Administrator\\Desktop\\File\\f\\van.txt","rw");
        FileChannel r = in.getChannel();
        FileChannel c = out.getChannel();

        long size = r.size();
        MappedByteBuffer insheBuff = r.map(FileChannel.MapMode.READ_ONLY,0,size); //输入流的映射
        MappedByteBuffer outsheBuff = c.map(FileChannel.MapMode.READ_WRITE,0,size); //输出流的映射
        for(int i=0;i<size;i++){
            outsheBuff.put(insheBuff.get());
        }
        r.close();
        c.close();
        in.close();
        out.close();
        System.out.println("复制映射完成");
    }
    /*比较IO操作性能排行
    1.内存映射最快
    2.nio读写文件
    3.加了缓存的io流
    4.不加缓存的io流
   */
    public static void main(String[] args) throws IOException {
        randomAccessFileCopy();
    }
}
